package com.spsoft.vatoutinv.service.vmscreditlimit.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.model.Result;
import com.spsoft.core.model.bo.TokenUser;
import com.spsoft.core.model.leqidmz.param.ApplyCreditParams;
import com.spsoft.core.model.leqidmz.param.BaseNsrRequestParams;
import com.spsoft.core.model.leqidmz.param.QueryCreditPeriodParams;
import com.spsoft.core.model.leqidmz.response.ApplyCreditVO;
import com.spsoft.core.model.leqidmz.response.QueryCreditPeriodVO;
import com.spsoft.core.model.leqidmz.response.QueryCreditlimitVO;
import com.spsoft.core.utils.BeanUtils;
import com.spsoft.core.utils.SecurityUtils;
import com.spsoft.einvoicetodmz.service.DmzApiClientService;
import com.spsoft.vatoutinv.constants.CommonConstant;
import com.spsoft.vatoutinv.entity.vmscreditlimit.*;
import com.spsoft.vatoutinv.enums.CommonEnum;
import com.spsoft.vatoutinv.enums.SxedUpdateEnum;
import com.spsoft.vatoutinv.mapper.*;
import com.spsoft.vatoutinv.model.vo.vmscreditlimit.VmsCreditlimitVO;
import com.spsoft.vatoutinv.service.vmscreditlimit.VmsCreditLimitApplyService;
import com.spsoft.vatoutinv.service.vmscreditlimit.VmsCreditLimitService;
import com.spsoft.vatoutinv.service.vmscreditlimit.VmsCreditLimitUpdateLogService;
import com.spsoft.vatoutinv.service.vmsfulloutinvoice.VmsFullOutInvoiceDetailsService;
import com.spsoft.vms.redis.RedisService;
import com.spsoft.vms.redis.constant.RedisConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 授信额度信息表 服务实现类
 * </p>
 *
 * @author wangy
 * @since 2023-11-24
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class VmsCreditLimitServiceImpl extends ServiceImpl<VmsCreditLimitMapper, VmsCreditLimit> implements VmsCreditLimitService {

    public static final String LOG_MSG = "(授信额度业务逻辑实现层)";

    private final RedisService redisService;

    private final DmzApiClientService dmzApiClientService;

    private final VmsCreditLimitMapper creditLimitMapper;

    private final VmsCreditLimitLogMapper creditLimitLogMapper;

    private final VmsCreditLimitApplyService creditLimitApplyService;

    private final VmsCreditLimitPeriodMapper creditLimitPeriodMapper;

    private final VmsCreditLimitPeriodLogMapper creditLimitPeriodLogMapper;

    private final VmsCreditLimitUpdateLogService creditLimitUpdateLogService;

    @Override
    @Transactional
    public Result<VmsCreditlimitVO> getCreditLimit() {
        VmsCreditlimitVO vo = new VmsCreditlimitVO();
        LambdaQueryWrapper<VmsCreditLimit> lq = new LambdaQueryWrapper<>();
        lq.eq(VmsCreditLimit::getDeptCode, SecurityUtils.getDeptCode());
        VmsCreditLimit one = getOne(lq);
        if (one != null) {
            one.setSq(one.getSq().substring(0, 4) + "-" + one.getSq().substring(4));
            BeanUtils.copyBeanProp(vo, one);
        }
        return Result.OK(vo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> getCreditLimitByLq(BaseNsrRequestParams params, TokenUser tokenUser) {
        // 有未上传成功的已开发票，不允许查询授信额度
        VmsFullOutInvoiceDetailsService vmsInvoiceDetailsService = SpringUtil.getBean(VmsFullOutInvoiceDetailsService.class);
        if (!vmsInvoiceDetailsService.checkUploadFull(tokenUser.getDeptCode())) {
            return Result.ERROR(ResponseEnum.CREDIT_LIMIT_QUERY_ERROR);
        }

        // 查询授信额度最小时间间隔为一个小时
        Page<VmsCreditLimitLog> page = new Page<>(1, 1);
        LambdaQueryWrapper<VmsCreditLimitLog> query = new LambdaQueryWrapper<>();
        query.eq(VmsCreditLimitLog::getDeptCode, tokenUser.getDeptCode());
        query.orderByDesc(VmsCreditLimitLog::getId);
        Page<VmsCreditLimitLog> resultPage = creditLimitLogMapper.selectPage(page, query);
        if (CollectionUtil.isNotEmpty(resultPage.getRecords())) {
            Date createTime = resultPage.getRecords().get(0).getCreateTime();
            long betweenHour = DateUtil.between(new Date(), createTime, DateUnit.HOUR);
            if (betweenHour < 1) {
                return Result.ERROR(ResponseEnum.CREDIT_LIMIT_TIME_ERROR);
            }
        }

        String redisLockKey = String.format(RedisConstant.REDIS_SYED_YFM_LOCK_KEY, tokenUser.getDeptCode());
        RLock lock = redisService.getLock(redisLockKey);
        boolean success = redisService.tryLock(lock, 3, 500);
        if (!success) {
            log.info("{}尝试指定次数后均未获取到锁，返回系统繁忙", LOG_MSG);
            return Result.ERROR(ResponseEnum.REDIS_LOCK_NO_GET);
        }
        log.info("{}redisson上锁成功，key：{}", LOG_MSG, redisLockKey);

        try {
            // 调用乐企接口 更新数据、更新日志数据
            Result<QueryCreditlimitVO> result = dmzApiClientService.queryCreditLimit(params, null);

            // 先记录日志操作
            VmsCreditLimitLog vmsCreditLimitLog = new VmsCreditLimitLog();
            vmsCreditLimitLog.setDeptCode(tokenUser.getDeptCode());
            vmsCreditLimitLog.setNsrsbh(params.getNsrsbh());
            vmsCreditLimitLog.setCreateTime(new Date());
            vmsCreditLimitLog.setCreateUser(tokenUser.getUserCode());
            vmsCreditLimitLog.setCreateUsername(tokenUser.getUserName());

            if (ResponseEnum.SUCCESS.getCode().equals(result.getCode())) {
                log.info("{}调用DMZ查询授信额度信息成功", LOG_MSG);
                QueryCreditlimitVO data = result.getData();
                BeanUtils.copyProperties(data, vmsCreditLimitLog);
                vmsCreditLimitLog.setOperateStatus(CommonConstant.STR_01);
                vmsCreditLimitLog.setOperateMsg(JSONObject.toJSONString(data));
                creditLimitLogMapper.insert(vmsCreditLimitLog);

                // 查询数据库是否有记录，无则新增，有则更新
                LambdaQueryWrapper<VmsCreditLimit> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(VmsCreditLimit::getDeptCode, tokenUser.getDeptCode());
                VmsCreditLimit creditLimit = creditLimitMapper.selectOne(queryWrapper);

                VmsCreditLimit vmsCreditLimit = new VmsCreditLimit();
                // Bean转换
                BeanUtils.copyProperties(data, vmsCreditLimit);
                vmsCreditLimit.setLogId(vmsCreditLimitLog.getId());
                vmsCreditLimit.setDeptCode(tokenUser.getDeptCode());
                vmsCreditLimit.setNsrsbh(params.getNsrsbh());
                vmsCreditLimit.setUpdateTime(new Date());
                vmsCreditLimit.setUpdateUser(tokenUser.getUserCode());
                vmsCreditLimit.setUpdateUsername(tokenUser.getUserName());
                if (creditLimit != null && creditLimit.getId() != 0) {
                    vmsCreditLimit.setId(creditLimit.getId());
                    this.updateById(vmsCreditLimit);
                } else {
                    vmsCreditLimit.setCreateTime(new Date());
                    vmsCreditLimit.setCreateUser(tokenUser.getUserCode());
                    vmsCreditLimit.setCreateUsername(tokenUser.getUserName());
                    this.save(vmsCreditLimit);
                }

                // 记录已下载未使用额度变更日志
                VmsCreditLimitUpdateLog updateLog = new VmsCreditLimitUpdateLog();
                updateLog.setCreditId(vmsCreditLimit.getId());
                updateLog.setUpdateType(CommonConstant.SXED_SELECT);
                updateLog.setOldValue(creditLimit == null ? BigDecimal.ZERO : creditLimit.getYxzwsyed());
                updateLog.setNewValue(vmsCreditLimit.getYxzwsyed());
                updateLog.setUpdateValue(updateLog.getNewValue().subtract(updateLog.getOldValue()));
                updateLog.setUpdateSource(SxedUpdateEnum.SXED_SELECT.getName());
                updateLog.setUpdateUser(vmsCreditLimit.getUpdateUser());
                updateLog.setUpdateTime(vmsCreditLimit.getUpdateTime());
                updateLog.setUpdateUsername(vmsCreditLimit.getUpdateUsername());
                creditLimitUpdateLogService.save(updateLog);
            } else {
                log.error("{}调用DMZ查询授信额度信息失败，原因：{}", LOG_MSG, result.getMessage());
                vmsCreditLimitLog.setOperateStatus(CommonConstant.STR_02);
                vmsCreditLimitLog.setOperateMsg(result.getMessage());
                creditLimitLogMapper.insert(vmsCreditLimitLog);
                return Result.ERROR(result.getCode(), result.getMessage());
            }
            return Result.OK_MSG(ResponseEnum.QUERY_SUCCESS.getMsg());

        } catch (Exception e) {
            log.error("{}调用乐企接口查询授信额度异常", LOG_MSG, e);
            return Result.ERROR();
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                log.info("{}redisson释放锁成功，key为:{}", LOG_MSG, redisLockKey);
                lock.unlock();
            } else {
                log.error("{}redisson释放锁失败，key为:{}", LOG_MSG, redisLockKey);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> updateCreditLimitDateByLq(QueryCreditPeriodParams params, TokenUser tokenUser) {
        // 有未上传成功的已开发票，不允许调整授信额度有效期
        VmsFullOutInvoiceDetailsService vmsInvoiceDetailsService = SpringUtil.getBean(VmsFullOutInvoiceDetailsService.class);
        if (!vmsInvoiceDetailsService.checkUploadFull(tokenUser.getDeptCode())) {
            return Result.ERROR(ResponseEnum.CREDIT_LIMIT_DATE_ERROR);
        }

        String redisLockKey = String.format(RedisConstant.REDIS_SYED_YFM_LOCK_KEY, tokenUser.getDeptCode());
        RLock lock = redisService.getLock(redisLockKey);
        boolean success = redisService.tryLock(lock, 3, 500);
        if (!success) {
            log.info("{}尝试指定次数后均未获取到锁，返回系统繁忙", LOG_MSG);
            return Result.ERROR(ResponseEnum.REDIS_LOCK_NO_GET);
        }
        log.info("{}redisson上锁成功，key：{}", LOG_MSG, redisLockKey);

        try {
            // 调用乐企接口调整授信额度有效期
            Result<QueryCreditPeriodVO> result = dmzApiClientService.queryCreditPeriod(params, null);
            log.info("{}乐企返回调整授信额度有效期信息：{}", LOG_MSG, JSONObject.toJSONString(result));

            // 先记录日志操作
            VmsCreditLimitPeriodLog vmsCreditLimitPeriodLog = new VmsCreditLimitPeriodLog();
            vmsCreditLimitPeriodLog.setDeptCode(tokenUser.getDeptCode());
            vmsCreditLimitPeriodLog.setNsrsbh(params.getXsfnsrsbh());
            vmsCreditLimitPeriodLog.setCreateTime(new Date());
            vmsCreditLimitPeriodLog.setCreateUser(tokenUser.getUserCode());
            vmsCreditLimitPeriodLog.setCreateUsername(tokenUser.getUserName());

            if (ResponseEnum.SUCCESS.getCode().equals(result.getCode())) {
                QueryCreditPeriodVO data = result.getData();
                vmsCreditLimitPeriodLog.setSq(data.getSxedsq());
                vmsCreditLimitPeriodLog.setSyqjq(data.getSyqjq());
                vmsCreditLimitPeriodLog.setSyqjz(data.getSyqjz());
                vmsCreditLimitPeriodLog.setOperateStatus(CommonConstant.STR_01);
                vmsCreditLimitPeriodLog.setOperateMsg(JSONObject.toJSONString(data));
                creditLimitPeriodLogMapper.insert(vmsCreditLimitPeriodLog);

                // 查询数据库是否有记录，无则新增，有则更新
                LambdaQueryWrapper<VmsCreditLimitPeriod> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(VmsCreditLimitPeriod::getDeptCode, tokenUser.getDeptCode());
                VmsCreditLimitPeriod creditLimitPeriod = creditLimitPeriodMapper.selectOne(queryWrapper);

                VmsCreditLimitPeriod vmsCreditLimitPeriod = new VmsCreditLimitPeriod();
                // Bean转换
                vmsCreditLimitPeriod.setSq(data.getSxedsq());
                vmsCreditLimitPeriod.setSyqjq(data.getSyqjq());
                vmsCreditLimitPeriod.setSyqjz(data.getSyqjz());
                vmsCreditLimitPeriod.setLogId(vmsCreditLimitPeriodLog.getId());
                vmsCreditLimitPeriod.setDeptCode(tokenUser.getDeptCode());
                vmsCreditLimitPeriod.setNsrsbh(params.getXsfnsrsbh());
                vmsCreditLimitPeriod.setUpdateTime(new Date());
                vmsCreditLimitPeriod.setUpdateUser(tokenUser.getUserCode());
                vmsCreditLimitPeriod.setUpdateUsername(tokenUser.getUserName());
                if (creditLimitPeriod != null && creditLimitPeriod.getId() != 0) {
                    vmsCreditLimitPeriod.setId(creditLimitPeriod.getId());
                    creditLimitPeriodMapper.updateById(vmsCreditLimitPeriod);
                } else {
                    vmsCreditLimitPeriod.setCreateTime(new Date());
                    vmsCreditLimitPeriod.setCreateUser(tokenUser.getUserCode());
                    vmsCreditLimitPeriod.setCreateUsername(tokenUser.getUserName());
                    creditLimitPeriodMapper.insert(vmsCreditLimitPeriod);
                }

                // 整授信额度有效期后，授信额度表也要更新
                LambdaQueryWrapper<VmsCreditLimit> query = new LambdaQueryWrapper<>();
                query.eq(VmsCreditLimit::getDeptCode, tokenUser.getDeptCode());
                VmsCreditLimit creditLimit = creditLimitMapper.selectOne(query);
                if (creditLimit != null) {
                    VmsCreditLimit vmsCreditLimit = new VmsCreditLimit();
                    vmsCreditLimit.setSq(vmsCreditLimitPeriod.getSq().replace("-", ""));
                    vmsCreditLimit.setSyqjq(vmsCreditLimitPeriod.getSyqjq());
                    vmsCreditLimit.setSyqjz(vmsCreditLimitPeriod.getSyqjz());
                    vmsCreditLimit.setUpdateTime(new Date());
                    vmsCreditLimit.setUpdateUser(tokenUser.getUserCode());
                    vmsCreditLimit.setUpdateUsername(tokenUser.getUserName());
                    vmsCreditLimit.setId(creditLimit.getId());
                    creditLimitMapper.updateById(vmsCreditLimit);
                }
                String msg = data.getSxedsq() + "，" + DateUtil.format(data.getSyqjq(), CommonConstant.DATE_FORMAT_8_SHORT)
                            + "-" + DateUtil.format(data.getSyqjz(), CommonConstant.DATE_FORMAT_8_SHORT);
                return Result.OK(msg);
            } else {
                vmsCreditLimitPeriodLog.setOperateStatus(CommonConstant.STR_02);
                vmsCreditLimitPeriodLog.setOperateMsg(result.getMessage());
                creditLimitPeriodLogMapper.insert(vmsCreditLimitPeriodLog);
                return Result.ERROR(result.getCode(), result.getMessage());
            }
        } catch (Exception e) {
            log.error("{}调用乐企接口调整授信额度有效期异常", LOG_MSG, e);
            return Result.ERROR();
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                log.info("{}redisson释放锁成功，key为:{}", LOG_MSG, redisLockKey);
                lock.unlock();
            } else {
                log.error("{}redisson释放锁失败，key为:{}", LOG_MSG, redisLockKey);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> applyCreditLimitByLq(ApplyCreditParams params, TokenUser tokenUser) {
        // 有未上传成功的已开发票，不允许下载/退回授信额度
        VmsFullOutInvoiceDetailsService vmsInvoiceDetailsService = SpringUtil.getBean(VmsFullOutInvoiceDetailsService.class);
        if (!vmsInvoiceDetailsService.checkUploadFull(tokenUser.getDeptCode())) {
            return Result.ERROR(ResponseEnum.CREDIT_LIMIT_APPLY_ERROR);
        }

        String redisLockKey = String.format(RedisConstant.REDIS_SYED_YFM_LOCK_KEY, tokenUser.getDeptCode());
        RLock lock = redisService.getLock(redisLockKey);
        boolean success = redisService.tryLock(lock, 3, 500);
        if (!success) {
            log.info("{}尝试指定次数后均未获取到锁，返回系统繁忙", LOG_MSG);
            return Result.ERROR(ResponseEnum.REDIS_LOCK_NO_GET);
        }
        log.info("{}redisson上锁成功，key：{}", LOG_MSG, redisLockKey);

        try {
            // 调用乐企接口并记录日志
            Result<ApplyCreditVO> result = dmzApiClientService.applyCredit(params, null);

            // 先记录日志操作
            VmsCreditLimitApply vmsCreditLimitApply = new VmsCreditLimitApply();
            vmsCreditLimitApply.setSqlx(params.getSqlx());
            vmsCreditLimitApply.setSqed(params.getSqed());
            vmsCreditLimitApply.setYwlsh(params.getYwlsh());
            vmsCreditLimitApply.setDeptCode(tokenUser.getDeptCode());
            vmsCreditLimitApply.setCreateTime(new Date());
            vmsCreditLimitApply.setCreateUser(tokenUser.getUserCode());
            vmsCreditLimitApply.setCreateUsername(tokenUser.getUserName());

            if (ResponseEnum.SUCCESS.getCode().equals(result.getCode())) {
                log.info("{}调用DMZ下载/退回授信额度成功", LOG_MSG);
                ApplyCreditVO data = result.getData();
                vmsCreditLimitApply.setOperateStatus(CommonConstant.STR_01);
                vmsCreditLimitApply.setOperateMsg(JSONObject.toJSONString(data));
                creditLimitApplyService.save(vmsCreditLimitApply);

                // 下载/退回授信额度成功后，更新本地授信额度表
                LambdaQueryWrapper<VmsCreditLimit> query = new LambdaQueryWrapper<>();
                query.eq(VmsCreditLimit::getDeptCode, tokenUser.getDeptCode());
                VmsCreditLimit creditLimit = creditLimitMapper.selectOne(query);
                if (creditLimit != null) {
                    VmsCreditLimit vmsCreditLimit = new VmsCreditLimit();
                    BigDecimal oldValue = creditLimit.getYxzwsyed();
                    if (CommonEnum.CREDIT_LIMIT_APPLY_TYPE_0.getKey().equals(params.getSqlx())) {
                        vmsCreditLimit.setKysyed(creditLimit.getKysyed().subtract(params.getSqed()));
                        vmsCreditLimit.setYxzed(creditLimit.getYxzed().add(params.getSqed()));
                        vmsCreditLimit.setYxzwsyed(oldValue.add(params.getSqed()));
                    } else {
                        vmsCreditLimit.setKysyed(creditLimit.getKysyed().add(params.getSqed()));
                        vmsCreditLimit.setYxzed(creditLimit.getYxzed().subtract(params.getSqed()));
                        vmsCreditLimit.setYxzwsyed(oldValue.subtract(params.getSqed()));
                    }
                    vmsCreditLimit.setSyqjq(data.getSyqjq());
                    vmsCreditLimit.setSyqjz(data.getSyqjz());
                    vmsCreditLimit.setUpdateTime(new Date());
                    vmsCreditLimit.setUpdateUser(tokenUser.getUserCode());
                    vmsCreditLimit.setUpdateUsername(tokenUser.getUserName());
                    vmsCreditLimit.setId(creditLimit.getId());
                    creditLimitMapper.updateById(vmsCreditLimit);

                    // 授信额度发生变化，变更记录表进行记录
                    VmsCreditLimitUpdateLog updateLog = new VmsCreditLimitUpdateLog();
                    updateLog.setCreditId(creditLimit.getId());
                    String updateSource;
                    if (CommonEnum.CREDIT_LIMIT_APPLY_TYPE_0.getKey().equals(params.getSqlx())) {
                        updateLog.setUpdateType(CommonEnum.CREDIT_LIMIT_APPLY_TYPE_0.getValue());
                        updateSource = SxedUpdateEnum.SXED_XZ.getName();
                    } else {
                        updateLog.setUpdateType(CommonEnum.CREDIT_LIMIT_APPLY_TYPE_1.getValue());
                        updateSource = SxedUpdateEnum.SXED_TH.getName();
                    }
                    updateLog.setOldValue(oldValue);
                    updateLog.setNewValue(vmsCreditLimit.getYxzwsyed());
                    updateLog.setUpdateValue(updateLog.getNewValue().subtract(updateLog.getOldValue()));
                    updateLog.setUpdateSource(updateSource);
                    updateLog.setUpdateUser(creditLimit.getUpdateUser());
                    updateLog.setUpdateTime(creditLimit.getUpdateTime());
                    updateLog.setUpdateUsername(creditLimit.getUpdateUsername());
                    creditLimitUpdateLogService.save(updateLog);
                }
            } else {
                log.error("{}调用DMZ下载/退回授信额度失败，原因：{}", LOG_MSG, result.getMessage());
                vmsCreditLimitApply.setOperateStatus(CommonConstant.STR_02);
                vmsCreditLimitApply.setOperateMsg(result.getMessage());
                creditLimitApplyService.save(vmsCreditLimitApply);
                return Result.ERROR(result.getCode(), result.getMessage());
            }
            return Result.OK();

        } catch (Exception e) {
            log.error("{}调用乐企接口下载/退回授信额度异常", LOG_MSG, e);
            return Result.ERROR();
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                log.info("{}redisson释放锁成功，key为:{}", LOG_MSG, redisLockKey);
                lock.unlock();
            } else {
                log.error("{}redisson释放锁失败，key为:{}", LOG_MSG, redisLockKey);
            }
        }
    }

    public VmsCreditLimit getSxedByDeptCode(String deptCode) {
        String nowTime = DateUtil.format(new Date(), CommonConstant.DATE_FORMAT_8);
        return creditLimitMapper.getSxedByDeptCode(deptCode, nowTime);
    }

    @Override
    @Transactional
    public Boolean updateSxed(String type, SxedUpdateEnum sxedUpdateEnum, BigDecimal jshjSum, VmsCreditLimit sxed, TokenUser tokenUser) {
        BigDecimal oldValue = sxed.getYxzwsyed();
        BigDecimal newValue;

        if (CommonConstant.SXED_ADD.equals(type)) {
            // 增加授信额度
            newValue = oldValue.add(jshjSum);
        } else if (CommonConstant.SXED_REDUCE.equals(type)) {
            // 减少授信额度
            newValue = oldValue.subtract(jshjSum);
        } else {
            return false;
        }
        // 变更的授信额度
        BigDecimal updateValue = newValue.subtract(oldValue);

        VmsCreditLimit creditLimit = new VmsCreditLimit();
        creditLimit.setId(sxed.getId());
        creditLimit.setYxzwsyed(newValue);
        creditLimit.setUpdateUser(tokenUser.getUserCode());
        creditLimit.setUpdateUsername(tokenUser.getUserName());
        creditLimit.setUpdateTime(new Date());

        boolean update = updateById(creditLimit);
        if (!update) {
            return false;
        }

        // 记录日志
        VmsCreditLimitUpdateLog updateLog = new VmsCreditLimitUpdateLog();
        updateLog.setCreditId(sxed.getId());
        updateLog.setUpdateType(type);
        updateLog.setOldValue(oldValue);
        updateLog.setNewValue(newValue);
        updateLog.setUpdateValue(updateValue);
        updateLog.setUpdateSource(sxedUpdateEnum.getName());
        updateLog.setUpdateUser(creditLimit.getUpdateUser());
        updateLog.setUpdateTime(creditLimit.getUpdateTime());
        updateLog.setUpdateUsername(creditLimit.getUpdateUsername());
        creditLimitUpdateLogService.save(updateLog);
        return true;
    }
}
